package xueqiu

import (
	"strings"

	"gitee.com/lenchu/stock-api-go/api"
)

const (
	_XQ_EXCHANGE_JJ  = "F"
	_XQ_EXCHANGE_SH  = "SH"
	_XQ_EXCHANGE_SZ  = "SZ"
	_XQ_EXCHANGE_HK  = ""
	_XQ_EXCHANGE_CSI = "CSI"
	_XQ_EXCHANGE_HKI = "HK"
)

type _XueqiuCode struct {
	symbol           string // SH600519			00700				SZ000002
	code             string // 600519				00700				000002
	exchange         string // SH												SZ
	standardCode     string // 600519.SH		00700.HK		000002.SZ
	standardCodeType string // SH						HK					SZ
}

var codeSplitMap = map[int64]int{
	11: 2,
	12: 2,
	13: 2,
	14: 2,
	23: 1,
	26: 2,
	30: 0,
	31: 2,
}
var codeTypeExMap = map[string]string{
	api.STOCK_TYPE_HK:  _XQ_EXCHANGE_HK,
	api.STOCK_TYPE_CSI: _XQ_EXCHANGE_CSI,
	api.STOCK_TYPE_JJ:  _XQ_EXCHANGE_JJ,
	api.STOCK_TYPE_HKI: _XQ_EXCHANGE_HKI,
	api.STOCK_TYPE_SH:  _XQ_EXCHANGE_SH,
	api.STOCK_TYPE_SZ:  _XQ_EXCHANGE_SZ,
}
var codeExTypeMap = make(map[string]string)

func init() {
	for k, v := range codeTypeExMap {
		codeExTypeMap[v] = k
	}
}

func newXueqiuCode(standardCodeType string, code string) *_XueqiuCode {
	r := _XueqiuCode{
		code:             code,
		standardCodeType: standardCodeType,
		exchange:         codeTypeExMap[standardCodeType],
		standardCode:     code + api.CODE_SUFFIX_SEPARATOR + standardCodeType,
		symbol:           codeTypeExMap[standardCodeType] + code,
	}
	return &r
}
func FromSymbolAndTypeToXueqiuCode(codeType int64, symbol string) *_XueqiuCode {
	splitIdx, exists := codeSplitMap[codeType]
	if !exists {
		return nil
	}
	prefix := symbol[0:splitIdx]
	code := symbol[splitIdx:]
	standardCodeType := codeExTypeMap[prefix]
	return newXueqiuCode(standardCodeType, code)
}
func FromStandardCodeToXueqiuCode(standardCode string) *_XueqiuCode {
	codeAndSuffix := strings.Split(standardCode, api.CODE_SUFFIX_SEPARATOR)
	return newXueqiuCode(codeAndSuffix[1], codeAndSuffix[0])
}

func (this *_XueqiuCode) isJJ() bool {
	return this.standardCodeType == api.STOCK_TYPE_JJ
}
